<template>
    <div style="width: 100vw;height: 100vh; overflow: hidden;" data-tauri-drag-region>
        <Cloud v-if="weatherData.desc.includes('多云') || weatherData.desc.includes('阴')" :opacity="opacity" :weatherData="weatherData" :mouse="mouseData"></Cloud>
        <Rain v-else-if="weatherData.desc.includes('雨')" :opacity="opacity" :weatherData="weatherData" :mouse="mouseData"></Rain>
        <SnowAll v-else-if="weatherData.desc.includes('雪')" :opacity="opacity" :weatherData="weatherData" :mouse="mouseData"></SnowAll>
        <Sun v-else :opacity="opacity" :weatherData="weatherData" :mouse="mouseData"></Sun>
    </div>
</template>
<script setup lang="ts">
import { useWindow } from '../hooks/useWindows'

import Sun from '../components/Sun.vue';
import Rain from '../components/Rain.vue';
import SnowAll from '../components/SnowAll.vue'
import Cloud from '../components/Cloud.vue'
import { onMounted, onUnmounted, ref } from 'vue';
import { invoke } from "@tauri-apps/api/core";

const opacity = ref(0.8);
const weatherData = ref({
    temp: 26,
    desc: '多云'

})

const mouseData = ref({
    x: 0,
    y: 0
})

const { getWebviewWindow } = useWindow();
let timer = 0;

const startLisenerMouse = async () => {
    await invoke('start_mouse_monitoring_command');
    clearInterval(timer)
    timer = setInterval(async () => {
        const res = await invoke('get_cached_mouse_position_command') as any;
        mouseData.value.x = res[0];
        mouseData.value.y = res[1];
    }, 20)
}

const initLisener = async () => {
    const win = await getWebviewWindow("desktopWidget")
    if (win) {
        // 监听透明度修改事件
        win.listen("updateDesktopOpacity", (value: any) => {
            opacity.value = 1 - value.payload
        })

        // 监听天气变化事件
        win.listen("currentWeatherChange", (value: any) => {
            weatherData.value = value.payload;
        })
    }
    // 监听鼠标移动
    startLisenerMouse();
}



onMounted(() => {
    initLisener();
})

onUnmounted(() => {
    if (timer) {
        clearInterval(timer)
    }
})


</script>